<template>
  <div class="app-container">

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['material:library:add']"
        >新增</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <!--素材库列表-->
    <el-row class="lib-list" :gutter="20">
      <el-col :span="4" v-for="(item, index) in libraryList" :key="index" >
        <el-card class="lib-card" :body-style="{ padding: '0px' }">
          <div class="img-div">
            <img :src="item.libCover" class="image">
          </div>
          <div style="padding: 14px;">
            <div class="name">{{item.libName}}</div>
            <div class="bottom clearfix">
              <el-button type="text" class="button" @click="handleUpdate(item)" v-hasPermi="['material:library:edit']">修改</el-button>
              <el-button type="text" class="button" @click="handleDelete(item)" v-hasPermi="['material:library:remove']">删除</el-button>
              <el-button type="text" class="button" @click="handleMaterial(item)" v-hasPermi="['cms:material:list']">素材</el-button>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改素材库对话框 -->
    <el-dialog :title="title" :visible.sync="open" v-if="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="名称" prop="libName">
          <el-input v-model="form.libName" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="封面" prop="libCover">
          <el-upload
            class="avatar-uploader"
            :action="url"
            :headers="headers"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 素材维护对话框 -->
    <el-dialog title="素材管理" :visible.sync="materialopen" v-if="materialopen" width="80%" append-to-body>
      <material :libraryId="libraryId"></material>
    </el-dialog>
  </div>
</template>

<script>
import { listLibrary, getLibrary, delLibrary, addLibrary, updateLibrary } from "@/api/cms/library";
import material from "./material"
import {mapGetters} from "vuex";
export default {
  name: "Library",
  dicts: ['sys_is_enable'],
  components: {material},
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 素材库表格数据
      libraryList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      materialopen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        libName: null,
        libCover: null,
        domain: null,
        isEnable: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      url:process.env.VUE_APP_BASE_API + '/common/oss/upload',
      imageUrl: '',
      libraryId: undefined
    };
  },
  computed: {
    ...mapGetters(['token']),
    headers() {
      return{
        "Authorization": this.token // 直接从本地获取token就行
      }
    }
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询素材库列表 */
    getList() {
      this.loading = true;
      listLibrary(this.queryParams).then(response => {
        this.libraryList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        libName: null,
        libCover: null,
        domain: null,
        isEnable: null,
        remark: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.imageUrl = '';
      this.open = true;
      this.title = "添加素材库";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.imageUrl = '';
      const id = row.id || this.ids
      getLibrary(id).then(response => {
        this.form = response.data;
        this.imageUrl = response.data.libCover;
        this.open = true;
        this.title = "修改素材库";
      });
    },
    /** 素材按钮操作 */
    handleMaterial(row) {
      this.libraryId = row.id;
      this.materialopen = true;
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateLibrary(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addLibrary(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id;
      this.$modal.confirm('是否确认删除素材库编号为"' + ids + '"的数据项？').then(function() {
        return delLibrary(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    handleAvatarSuccess(res, file) {

      // this.imageUrl = URL.createObjectURL(file.raw);
      this.imageUrl = res.data.url + res.data.fileName;
      this.form.libCover = this.imageUrl;
    },
    beforeAvatarUpload(file) {
      const isType = file.type === 'image/jpeg' || file.type === 'image/png'  || file.type === 'image/jpg';
      const isLt = file.size / 1024 / 1024 < 4;
      if (!isType) {
        this.$message.error('封面图片只能是 JPG、PNG 格式!!');
      }
      if (!isLt) {
        this.$message.error('上传图片大小不能超过4M!');
      }
      return isType && isLt;
    }
  }
};
</script>

<style lang="less" scoped>
  .lib-list{
    .lib-card {
      align-items: center;
      margin-bottom: 20px;
      height: 290px;
      .name {
        width: 100%;
        overflow: hidden;
        text-overflow:ellipsis;
        white-space: nowrap;
      }
      .img-div{
        display: flex;
        justify-content: center;
        align-items: center;
        width: 100%;
        .image {
          max-width: 100%;
          max-height: 100%;
          object-fit: contain;
          margin: 0 auto;
          display: block;
          height: 220px;
        }
      }

    }
  }

  .avatar-uploader {
    /deep/.el-upload {
      border: 1px dashed #df2727;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
    }
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
